<template>
  <div>
    <el-dialog
      :title="info.openType == 'edit' ? '修改分类' : '添加分类'"
      :visible.sync="info.dialogVisible"
      width="50%"
    >
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item prop="specsname" label="属性名">
          <el-input v-model="ruleForm.specsname"></el-input>
        </el-form-item>
        <el-form-item label="属性值" prop="attrs">
          <div v-for="(item, index) in attrsList" :key="index">
            <el-input v-model="item.value"></el-input>
            <el-button v-if="index" @click.prevent="removeItem(index)">删除属性</el-button>
            <el-button v-else @click="addItem">新增属性</el-button>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="info.openType === 'edit'"
            type="primary"
            class="btn1"
            @click="submitForm"
            >立即修改</el-button
          >
          <el-button v-else type="warning" class="btn1" @click="submitForm"
            >立即添加</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { cateAddFn, cateEditFn } from "../../request";
export default {
  props: ["info"],
  data() {
    return {
      // 对话框是否显示
      dialogVisible: false,
      // 属性值的数组
      attrsList: [{value: ''}],
      ruleForm: {
        specsname: "",
        attrs: [],
        status: 1,
      },
    };
  },
  methods: {
    // 删除一项
    removeItem(index) {
      this.attrsList.splice(index, 1)
    },
    // 新增一项
    addItem() {
      if(this.attrsList.length == 5) {
        this.$message.warning(`最多添加5项！`);
      }else {
        this.attrsList.push({
          value: ""
        });
      }
    },
    // 设置弹窗中的值
    setStatus(data) {
      this.ruleForm = data;
    },
    // 提交表单
    submitForm() {
      // this.$refs.ruleForm  选择表单，目的是为了校验表单
      // validate  element自带的方法，用来校验
      this.$refs.ruleForm.validate(async (valid) => {
        // valid为真时表示校验否过
        if (valid) {
        //  遍历attrsList，将它的值赋值给this.ruleFrom.attrs
          var res;
          if (this.info.openType === "edit") {
            // edit,是修改
            res = await cateEditFn(this.ruleFrom);
          } else {
            // add，是新增
            res = await cateAddFn(this.ruleFrom);
          }
          if (res === "操作成功") {
            // 关闭弹窗
            this.$emit("close");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style>
</style>